package com.sgb.kjwl.view.ui.fragment.enterprise;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentCopyrightPublishBinding;
import com.sgb.kjwl.model.entity.enterprise.IpPickSelectEntity;
import com.sgb.kjwl.model.entity.enterprise.PublishCopyrightDetailEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.utils.KeyboardUtils;
import com.sgb.kjwl.utils.PickerHelper;
import com.sgb.kjwl.utils.PointUtils;
import com.sgb.kjwl.utils.UploadCheckHelper;
import com.swgk.core.event.EventConstant;
import com.sgb.link.event.LeaseEvent;
import com.sgb.kjwl.view.ui.activity.enterprise.MakeOverPublishActivity;
import com.sgb.kjwl.viewmodel.enterprise.PublishViewModel;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CopyrightPublishFragment extends AppFragment {

    FragmentCopyrightPublishBinding mBinding;
    PublishViewModel mViewModel;
    private PublishCopyrightDetailEntity mEntity;
    private String mId = "", mCategory, mCategoryName, mAuthorizationMethod, image = "";
    private long mTime;
    private OptionsPickerView<IpPickSelectEntity> mOptionsPickerView;
    private MakeOverPublishActivity mActivity;
    private List<File> list = new ArrayList<>();
    private boolean isChecked, isCheckedExclusive, isCheckedNoExclusive;
    private int position;

    public static CopyrightPublishFragment newInstance() {
        CopyrightPublishFragment tradePublishFragment = new CopyrightPublishFragment();
        return tradePublishFragment;
    }

    public static CopyrightPublishFragment newInstance(PublishCopyrightDetailEntity entity) {
        CopyrightPublishFragment tradePublishFragment = new CopyrightPublishFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("entity", entity);
        tradePublishFragment.setArguments(bundle);
        return tradePublishFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_copyright_publish, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding.setLifecycleOwner(this);
        mViewModel = new ViewModelProvider(this).get(PublishViewModel.class);

        initCheckBox();
        initButton();
        initData();
    }

    private void initCheckBox() {
        mBinding.deleteTv.setVisibility(View.GONE);

        mBinding.rbFragmentTradePublishMakeoverSelectorPrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isChecked = !isChecked;
                if (isChecked) {
                    mBinding.ivYijia.setImageResource(R.mipmap.gouxuan_makeover_publish_price);
                    mBinding.etFragmentTradePublishMakeoverMuchEdit.setEnabled(false);
                    mBinding.etFragmentTradePublishMakeoverMuchEdit.setText("请输入价格");
                    mBinding.etFragmentTradePublishMakeoverMuchEdit.setTextColor(getResources().getColor(R.color.color_C0C4CC));
                } else {
                    mBinding.etFragmentTradePublishMakeoverMuchEdit.setEnabled(true);
                    mBinding.ivYijia.setImageResource(R.mipmap.weigouxuan_makeover_publish_price);
                    mBinding.etFragmentTradePublishMakeoverMuchEdit.setText("");
                    mBinding.etFragmentTradePublishMakeoverMuchEdit.setTextColor(getResources().getColor(R.color.FF000000));
                }
            }
        });
        mBinding.rbFragmentCopyrightPublishExclusive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAuthorizationMethod = "1";
                if (!mBinding.ivTag1.isSelected()) {
                    mBinding.ivTag1.setSelected(true);
                }
                mBinding.ivTag5.setSelected(false);
            }
        });

        mBinding.rbFragmentCopyrightPublishNonExclusive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAuthorizationMethod = "2";
                if (!mBinding.ivTag5.isSelected()) {
                    mBinding.ivTag5.setSelected(true);
                }
                mBinding.ivTag1.setSelected(false);
            }
        });
    }

    private void initButton() {
        mBinding.tvFragmentCopyrightPublishSelectType.setOnClickListener(this);
        mBinding.tvFragmentTradePublishDurationOfAuthorization.setOnClickListener(this);
        mBinding.ivFragmentCopyrightPublishUploadPicture.setOnClickListener(this);
        mBinding.deleteTv.setOnClickListener(this);
    }

    private void initData() {
        if (getArguments() != null) {
            mEntity = (PublishCopyrightDetailEntity) getArguments().getSerializable("entity");
        }

        if (mEntity != null) {
            mId = mEntity.getId() + "";
            image = mEntity.getImg();
            mCategoryName = mEntity.getCategoryName();
            mAuthorizationMethod = mEntity.getAuthorizationMethod() + "";
            mTime = mEntity.getAuthorizationPeriod();

            mBinding.tvFragmentCopyrightPublishSelectType.setText(mEntity.getCategoryName());
            mBinding.etFragmentCopyPublishTradeNameEdit.setText(mEntity.getName());
            mBinding.etFragmentCopyrightPublishRegisterNumEdit.setText(mEntity.getRegistrationNo());
            mBinding.etFragmentCopyrightPublishRegisterNameEdit.setText(mEntity.getCopyrightOwner());

            if (mEntity.getPrice() == -1) {
                isChecked = true;
                mBinding.ivYijia.setImageResource(R.mipmap.gouxuan_makeover_publish_price);
                mBinding.etFragmentTradePublishMakeoverMuchEdit.setEnabled(false);
                mBinding.etFragmentTradePublishMakeoverMuchEdit.setText("请输入价格");
                mBinding.etFragmentTradePublishMakeoverMuchEdit.setTextColor(getResources().getColor(R.color.color_C0C4CC));
            } else {
                mBinding.etFragmentTradePublishMakeoverMuchEdit.setEnabled(true);
                mBinding.ivYijia.setImageResource(R.mipmap.weigouxuan_makeover_publish_price);
                mBinding.etFragmentTradePublishMakeoverMuchEdit.setText(PointUtils.originalPrice(mEntity.getPrice()));
                mBinding.etFragmentTradePublishMakeoverMuchEdit.setTextColor(getResources().getColor(R.color.FF000000));
            }

            mAuthorizationMethod = mEntity.getAuthorizationMethod() + "";
            if (mEntity.getAuthorizationMethod() == 1) {
                mBinding.ivTag1.setSelected(true);
                mBinding.ivTag5.setSelected(false);
                isCheckedExclusive = true;
            } else {
                mBinding.ivTag1.setSelected(false);
                mBinding.ivTag5.setSelected(true);
                isCheckedNoExclusive = true;
            }
            mBinding.etFragmentCopyrightPublishLinkman.setText(mEntity.getContacts());
            mBinding.etFragmentCopyrightPublishPhone.setText(mEntity.getContactNumber());
            mBinding.etFragmentCopyrightPublishMakeCircle.setText(mEntity.getDescription());
            mBinding.tvFragmentTradePublishDurationOfAuthorization.setText(DateUtils.timestampToDate(mEntity.getAuthorizationPeriod()));

            Glide.with(getContext()).load(mEntity.getImg()).apply(new RequestOptions()
                    .placeholder(R.mipmap.makeover_add_picture)
                    .fallback(R.mipmap.makeover_add_picture)
                    .error(R.mipmap.makeover_add_picture)).into(mBinding.ivFragmentCopyrightPublishUploadPicture);
        }

        mViewModel.getCopyrightTypeOption(getContext());
        mViewModel.mCopyrightTypeListLiveData.observe(getViewLifecycleOwner(), new Observer<List<IpPickSelectEntity>>() {
            @Override
            public void onChanged(List<IpPickSelectEntity> ipPickSelectEntities) {
                for (int i = 0; i < ipPickSelectEntities.size(); i++) {
                    if (ipPickSelectEntities.get(i).getName().equals(mBinding.tvFragmentCopyrightPublishSelectType.getText().toString())) {
                        position = i;
                    }
                }
                if (mOptionsPickerView == null) {
                    mOptionsPickerView = new OptionsPickerBuilder(getContext(), new OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int options2, int options3, View v) {
                            mBinding.tvFragmentCopyrightPublishSelectType.setText(ipPickSelectEntities.get(options1).getName());
                            mCategory = ipPickSelectEntities.get(options1).getValue();
                            mCategoryName = ipPickSelectEntities.get(options1).getName();
                        }
                    }).setCancelText("取消").setSubCalSize(15)
                            .setCancelColor(Color.parseColor("#666666"))
                            .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                            .setSubmitText("确定")
                            .setSubmitColor(Color.parseColor("#5792FD"))
                            .setTextColorCenter(Color.parseColor("#ff333333"))
                            .setContentTextSize(15)
                            .setLineSpacingMultiplier(2.5f)
                            .setDividerColor(Color.parseColor("#EDEDED"))
                            .setDecorView(getActivity().getWindow().getDecorView().findViewById(android.R.id.content)).build();
                    mOptionsPickerView.setPicker(ipPickSelectEntities);
                    mOptionsPickerView.setSelectOptions(position);
                    mOptionsPickerView.setTitleText("选择版权分类");
                }
                KeyboardUtils.hideSoftInput(getActivity());
            }
        });
        mActivity = (MakeOverPublishActivity) getActivity();
        mViewModel.uploadFileSuccess.observe(getViewLifecycleOwner(), new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> list) {
                image = list.get(0);
                upload();
            }
        });

        mViewModel.mSaveSuccessCopyright.observe(getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
//                getActivity().setResult(2);
                EventBus.getDefault().postSticky(LeaseEvent.make().setMessageTag(EventConstant.EVENT_CREATE_NEWMAKEOVERDATA).setObject(2));
                getActivity().finish();
//                ActivityJump.jumpToActivity(getContext(), MakeOverPublishMainActivity.class, Pair.create("position", 2));
            }
        });


    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity.mLiveData.observe(getViewLifecycleOwner(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    if (!UploadCheckHelper.textCheck(getContext(), new TextView[]{mBinding.tvFragmentCopyrightPublishSelectType, mBinding.etFragmentCopyPublishTradeNameEdit
                                    , mBinding.etFragmentCopyrightPublishRegisterNumEdit, mBinding.etFragmentCopyrightPublishRegisterNameEdit, mBinding.etFragmentTradePublishMakeoverMuchEdit
                                    , mBinding.etFragmentCopyrightPublishLinkman, mBinding.etFragmentCopyrightPublishPhone}
                            , new String[]{"版权分类", "版权名称", "登记号", "著作权人", "价格", "联系人姓名", "联系电话"})) {
                        return;
                    }
                    if(mBinding.etFragmentTradePublishMakeoverMuchEdit.isEnabled()&&Double.parseDouble(mBinding.etFragmentTradePublishMakeoverMuchEdit.getText().toString())==0){
                        MToast.showToast(getContext(), "交易价格大于0");
                    }
                    if (!mBinding.ivTag1.isSelected() && !mBinding.ivTag5.isSelected()) {
                        MToast.showToast(getContext(), "请选择授权方式");
                        return;
                    }
                    if (TextUtils.isEmpty(mBinding.tvFragmentTradePublishDurationOfAuthorization.getText().toString().trim())) {
                        MToast.showToast(getContext(), "请选择授权期限");
                        return;
                    }
                    if (!CheckUtils.isMobileForService(mBinding.etFragmentCopyrightPublishPhone.getText().toString().trim())) {
                        MToast.showToast(getContext(), "请输入正确的电话格式");
                        return;
                    }

                    if (image.equals("") && list.size() <= 0) {
                        MToast.showToast(getContext(), "请上传版权图片");
                        return;
                    }

                    if (image.equals("")) {
                        mViewModel.uploadPicture(getContext(), list);
                    } else {
                        upload();
                    }
                }
            }
        });
    }

    private void initFileSelector() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .compress(true)//是否压缩
                .minimumCompressSize(4 * 1024)//小于4M不压缩
                .maxSelectNum(1)//判断还能选多少张图片
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_fragment_copyright_publish_select_type:
                if (mOptionsPickerView != null) {
                    mOptionsPickerView.show();
                } else {
                    mViewModel.getCopyrightTypeOption(getContext());
                }
                break;
            case R.id.tv_fragment_trade_publish_duration_of_authorization:
                PickerHelper.with(getContext()).getCommonTimeBuild("", new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        mTime = date.getTime();
                        mBinding.tvFragmentTradePublishDurationOfAuthorization.setText(DateUtils.timestampToDate(mTime));
                    }
                }).setCancelText("取消").setSubCalSize(15)
                        .setCancelColor(Color.parseColor("#666666"))
                        .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                        .setSubmitText("确定")
                        .setSubmitColor(Color.parseColor("#5792FD"))
                        .setTextColorCenter(Color.parseColor("#ff333333"))
                        .setContentTextSize(15)
                        .setLineSpacingMultiplier(2.5f)
                        .setDividerColor(Color.parseColor("#EDEDED"))
                        .build().show();
                break;
            case R.id.iv_fragment_copyright_publish_upload_picture:
                initFileSelector();
                break;
            case R.id.delete_tv:
                mBinding.ivFragmentCopyrightPublishUploadPicture.setImageResource(R.mipmap.makeover_add_picture);
                list.clear();
                break;
        }
    }

    public void upload() {
//        if (!CheckUtils.isMobile(mBinding.etFragmentCopyrightPublishPhone.getText().toString())){
//            MToast.showToast(getContext(),"请输入正确的电话格式");
//            return;
//        }
        /**
         author	T文本	是
         作者
         */

        String companyNo = "0";
        String teamNo = "0";
        String user = "0";
        if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 1) {
            companyNo = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, "");
        } else if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 2) {
            teamNo = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, "");
        } else {
            user = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO, "");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("id", mId);
        map.put("category", mCategory);
        map.put("categoryName", mCategoryName);
        map.put("name", mBinding.etFragmentCopyPublishTradeNameEdit.getText().toString());
        map.put("registrationNo", mBinding.etFragmentCopyrightPublishRegisterNumEdit.getText().toString());
        map.put("author", "");
        map.put("copyrightOwner", mBinding.etFragmentCopyrightPublishRegisterNameEdit.getText().toString());
        map.put("price", mBinding.etFragmentTradePublishMakeoverMuchEdit.getText().toString().equals("请输入价格") ? "-1" : mBinding.etFragmentTradePublishMakeoverMuchEdit.getText().toString());
        map.put("authorizationMethod", mAuthorizationMethod);
        map.put("authorizationPeriod", mTime);
        map.put("contactNumber", mBinding.etFragmentCopyrightPublishPhone.getText().toString());
        map.put("contacts", mBinding.etFragmentCopyrightPublishLinkman.getText().toString());
        map.put("description", mBinding.etFragmentCopyrightPublishMakeCircle.getText().toString());
        map.put("companyNo", companyNo);
        map.put("userNo", user);
        map.put("img", image);
//        map.put("salePrice",mBinding.etFragmentPropertyPublishBuyPriceEdit.getText().toString());
//        map.put("assetsName",mBinding.etFragmentPropertyPublishNameEdit.getText().toString());
        map.put("publishType", SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0));
        if (SharedPreferenceUtil.getInstance().getSaveIntData(SharedPreferenceUtil.COM_TYPE, 0) == 0) {
            map.put("realName", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.REAL_NAME, ""));
        } else {
            map.put("realName", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NAME, ""));
        }
        map.put("teamNo", teamNo);
        map.put("telPhone", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LOGIN_PHONE, ""));
        map.put("companyName", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NAME, ""));
        mViewModel.saveAndUpdateCopyright(getContext(), map);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            list.clear();
            List<LocalMedia> imageList = PictureSelector.obtainMultipleResult(data);
            if (imageList == null || imageList.size() == 0) return;
            image = "";
            //获取压缩图片
            for (LocalMedia localMedia : imageList) {
                list.add(new File(localMedia.getCompressPath()));
            }

            Glide.with(getContext()).load(list.get(0)).into(mBinding.ivFragmentCopyrightPublishUploadPicture);
            mBinding.deleteTv.setVisibility(View.VISIBLE);
        }

    }
}
